package com.kingsoft.dc.khaos.module.spark.model.exchangefile.control;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;

import java.io.OutputStream;
import java.net.URI;

/**
 * Created by jing on 19/2/27.
 */
public class ControlFileUtils {
    public static void genControlFile(ControlFile file, String fileName) {
        Document document = DocumentHelper.createDocument();
        Element transmitContent = document.addElement("transmit-content");
        Element transmitContentFile = transmitContent.addElement("file");

        //
        Element e1 = transmitContentFile.addElement("datatype");
        e1.addText(file.getDataType());

        Element e2 = transmitContentFile.addElement("filename");
        e2.addText(file.getFileName());

        Element e3 = transmitContentFile.addElement("recordnum");
        e3.addText(file.getRecordNum());

        Element e4 = transmitContentFile.addElement("filesize");
        e4.addText(file.getFileSize());

        Element e5 = transmitContentFile.addElement("starttimestamp");
        e5.addText(file.getStarttimestamp());

        Element e6 = transmitContentFile.addElement("endtimestamp");
        e6.addText(file.getEndtimestamp());

        try {
            Configuration conf = new Configuration();
            FileSystem fs = FileSystem.get(URI.create(fileName), conf);
            OutputStream out = fs.create(new Path(fileName));
            OutputFormat format = OutputFormat.createPrettyPrint();
            format.setEncoding("UTF-8");
            XMLWriter xmlWriter = new XMLWriter(out, format);
            xmlWriter.write(document);
            xmlWriter.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
    }
}
